package kr.ne.jay.SimpleString;
import android.content.Context;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class StringView extends SurfaceView implements SurfaceHolder.Callback {
	private SimString m_simString;
	private StringThread m_thread;
	private static final int numSegment = 20;
	private static final int lenSegment = 10;
	
	public StringView(Context context) {
		super (context);

		SurfaceHolder holder = getHolder();
		holder.addCallback(this);
		holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
		m_simString = new SimString();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			m_simString.AddTouchConstraint(new Vector2f(event.getX(), event.getY()));
			return true;
		case MotionEvent.ACTION_UP:
			m_simString.RemoveTouchConstraint();
			return true;
		case MotionEvent.ACTION_MOVE:
			m_simString.MoveTouchConstraint(new Vector2f(event.getX(), event.getY()));
			return true;
		default:
			break;
		}
		return false;
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldW, int oldH) {
		super.onSizeChanged(w, h, oldW, oldH);
		initSimulation(w/2);
	}
	
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		m_thread = new StringThread(holder, m_simString);
		if (Settings.getColorOption(getContext()))
			m_thread.setLineColor(Color.BLUE);
		m_thread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		m_thread.requestExitAndWait();
		m_thread = null;
	}	

	private void initSimulation(int orgX) {
		m_simString.clear();
		for (int i=0; i<numSegment; ++i) {
			m_simString.addPoint(new Vector2f(orgX+i*lenSegment, i*lenSegment));
		}
		m_simString.init();
	}

	public void addAcceleration(final float[] acc) {
		m_simString.addAcceleration(new Vector2f(acc[0], acc[1]));
	}
}
